/**
 * Copyright (c) 2012, David Varbel
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * 
 * 1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * 2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.epistrata.neutraltheory;

public class BooleanArrayCritter extends Critter {
	protected boolean[] genome;

	private BooleanArrayCritter() {
		
	}
	
	/**
	 * Static factory method that returns a new clone critter for use in the initial population
	 * @param model
	 * @return
	 */
	public static BooleanArrayCritter newRandomInstance(NeutralTheoryModel model) {
		if (model == null) {
			throw new IllegalArgumentException("A non-null Model must be provided.");
		}

		BooleanArrayCritter randomInstance = new BooleanArrayCritter();
		randomInstance.model = model;
		randomInstance.random = model.getRandom();
		
		//create random genome
		randomInstance.genome = new boolean[model.getGenomeSize()];
		for (int i = 0; i < randomInstance.genome.length; i++) {
			randomInstance.genome[i] = randomInstance.random.nextBoolean();
		}

		randomInstance.setLocation(	randomInstance.random.nextDouble() * model.getWorldXSize(),
									randomInstance.random.nextDouble() * model.getWorldYSize());

		return randomInstance;
	}
	
	public BooleanArrayCritter clone() {
		BooleanArrayCritter clone = new BooleanArrayCritter();
		clone.model = this.model;
		clone.random = this.random;
		
		clone.genome = new boolean[this.genome.length];
		for (int i = 0; i < this.genome.length; i++) {
			clone.genome[i] = this.genome[i];
		}
		clone.setLocation(	random.nextDouble() * model.getWorldXSize(),
				random.nextDouble() * model.getWorldYSize());
		
		return clone;
	}
	
	/**
	 * Factory method that returns a new offspring critter and a new genome
	 * @param model
	 * @return
	 */
	private BooleanArrayCritter newOffspringInstance(double[] parentLocation, boolean[] offspringGenome, boolean disperse) {
		assert parentLocation != null;
		assert offspringGenome != null;
		assert offspringGenome.length == model.getGenomeSize();

		
		BooleanArrayCritter offspring = new BooleanArrayCritter();
		offspring.genome = offspringGenome;
		offspring.model = this.model;
		offspring.random = this.random;
		
		//Disperse or keep parent location
		if (disperse && random.nextDouble() < model.getDispersalProbability()) {
			offspring.randomizeLocation(parentLocation);
		}
		else {
			offspring.setLocation(parentLocation[0], parentLocation[1]);
		}
		
		return offspring;
	}
	
	public Critter mateWith(Critter mate) {
		assert mate instanceof BooleanArrayCritter;
		
		//Crossover
		boolean[] offspringGenome = crossover(((BooleanArrayCritter)mate).genome);
		
		//Mutate
		offspringGenome = mutate(offspringGenome);
		
		//Create offspring
		BooleanArrayCritter offspring = newOffspringInstance(getLocation(), offspringGenome, true);
		
		//delete parent from grid
		currentGridCell.removeCritter(this);
		
		return offspring;
	}
	
	
	public Critter mateOpportunistWith(Critter mate, Critter earlyDeathCritter) {
		assert mate instanceof BooleanArrayCritter;
		
		//Crossover
		boolean[] offspringGenome = crossover(((BooleanArrayCritter)mate).genome);
		
		//Mutate
		offspringGenome = mutate(offspringGenome);
		
		//Create offspring
		BooleanArrayCritter offspring = newOffspringInstance(earlyDeathCritter.getLocation(), offspringGenome, false);

		//delete early death critter (instead of parent who isn't being replaced) from grid
		earlyDeathCritter.currentGridCell.removeCritter(earlyDeathCritter);

		return offspring;
	}
	
	private boolean[] crossover(boolean[] mateGenome) {
		assert mateGenome != null;
		assert genome.length == mateGenome.length;
				
		int crossoverLocation = random.nextInt(genome.length);
		boolean[] offspringGenome = new boolean[genome.length];
		for (int i = 0; i < crossoverLocation; i++) {
			offspringGenome[i] = genome[i];
		}
		for (int i = crossoverLocation; i < mateGenome.length; i++) {
			offspringGenome[i] = mateGenome[i];
		}

		return offspringGenome;
	}
	
	private boolean[] mutate(boolean[] offspringGenome) {
		assert offspringGenome != null;
		assert offspringGenome.length > 0;
		
		for (int i = 0; i < offspringGenome.length; i++) {
			if (random.nextDouble() < model.getMutationProbability()) {
				offspringGenome[i] = !offspringGenome[i];
			}
		}
		
		return offspringGenome;
		
	}
	
	/**
	 * Check if this critter is in the same species with the other critter by
	 * comparing their genes and determining if the total distance is smaller
	 * than the allowed genetic difference in the configuration.
	 * 
	 * @param other a Critter to compare
	 * @param maxDistance maximum allowed distance
	 * @return true or false
	 */
	public boolean isSameSpecies(Critter other, int maxDistance) {
		assert other instanceof BooleanArrayCritter;
		assert maxDistance > 0;
		
		int distance = 0;
		//assumes equal genetic length
		BooleanArrayCritter baOther = ((BooleanArrayCritter)other);
		for (int i = 0; i < genome.length; i++) {
			if (genome[i] != baOther.genome[i]) {
				distance += 1;
			}
		}
		
		if (distance <= maxDistance) {
			return true;
		}
		else {
			return false;			
		}
	}

	@Override
	public double[] getDoubleGenomeForPca() {
		double[] doubleGenome = new double[genome.length];
		for (int i = 0; i < genome.length; i++) {
			doubleGenome[i] = genome[i] ? 1.0 : 0.0;
		}

		return doubleGenome;
	}

}
